
package org.zfes.snowier.common.monitor.router;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zfes.snowier.common.monitor.biz.dao.MysqlAcutorMapper;
import org.zfes.snowier.common.monitor.biz.dao.ZActuatorMapper;
import org.zfes.snowier.common.monitor.biz.dao.ZUserMapper;
import org.zfes.snowier.common.monitor.biz.model.MysqlAcutor;
import org.zfes.snowier.common.monitor.biz.model.ZActuatorEntity;
import org.zfes.snowier.common.monitor.biz.model.ZUserEntity;
import org.zfes.snowier.common.monitor.biz.service.ZActuatorService;
import org.zfes.snowier.common.monitor.biz.vo.MysqlActuatorVo;
import org.zfes.snowier.common.monitor.biz.vo.ZActuatorVo;
import org.zfes.snowier.common.monitor.jvm.Server;
import org.zfes.snowier.common.monitor.util.Md5;
import org.zfes.snowier.common.monitor.utils.Res;
import org.zfes.snowier.common.monitor.warn.email.IEmailService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.gson.Gson;

@Controller
public class ZActuatorController {
    public Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private ZUserMapper sysUserMapper;
	@Autowired
	private ZActuatorMapper sysActuatorMapper;
	@Autowired
	private MysqlAcutorMapper mysqlAcutorMapper;
	
	@Autowired
	private ZActuatorService actuatorService;
	
    @RequestMapping(value = "/")
    public String localhost(ModelMap model){
        return "login";
    }

 
    @RequestMapping(value = "/login")
    public String tologin(ModelMap model){
        return "login";
    }

    @RequestMapping(value = "/logout")
    public String logiout(HttpServletRequest request){
    	request.getSession().removeAttribute("username");
        return "login";
    }
      

	@ResponseBody
    @RequestMapping("/doLogin")
    public Res login(String uname,String pwd,HttpServletRequest request) {
    	if(StringUtils.isEmpty(uname)||StringUtils.isEmpty(pwd)){
    		return Res.error("啥都不说，不让进");
    	}
    	Map<String, Object> paramMap=new HashMap<>();
    	paramMap.put("name", uname);
    	ZUserEntity user =sysUserMapper.selectOne(new QueryWrapper(paramMap));
        if (user == null || !user.getPassword().equals(Md5.encode(pwd))){
            return Res.error("口令错误");
        }else{
        	request.getSession().setAttribute("username", user.getName());
			return Res.ok();
        }
    }
	
	
    @RequestMapping(value = "/index")
    public String index(ModelMap model,HttpServletRequest request){
    	List<ZActuatorEntity> list=sysActuatorMapper.selectList(null);
    	model.addAttribute("list",list);
    	model.addAttribute("username",request.getSession().getAttribute("username"));
        return "index";
    }
    
   
  
    @RequestMapping(value = "/main")
    public String main(ModelMap mmap) throws IOException{
    	 
    	List<JSONObject> server=Lists.newArrayList();
    	List<ZActuatorEntity> actuatorList=sysActuatorMapper.selectList(null);
    	  
    	actuatorList.forEach(act->{
    		 JSONObject info=JSONObject.parseObject(act.getServerInfo());
    		 info.put("name", act.getName());
    		 info.put("url",act.getUrl());
    		 info.put("groupKey",act.getGroupKey());
    		 info.put("instanceKey",act.getInstanceKey());
    		 server.add(info);   
    	});
    	mmap.put("list",server);
        return "main";
    } 
    
    @RequestMapping(value = "/list")
    public String list(ModelMap mmap) throws IOException{
    
        return "list";
    }

    @RequestMapping(value = "/mysqllist")
    public String mysqllist(ModelMap mmap) throws IOException{
    	
        return "mysqllist";
    }
    
    @RequestMapping(value = "/detail")
    public String detail(ModelMap mmap) throws IOException{
    
        return "detail";
    }
    @RequestMapping(value = "/monitor")
    public String monitor(){
        return "monitor";
    }
    
    @RequestMapping(value = "/mysqlmonitor")
    public String mysqlmonitor(){
        return "mysqlmonitor";
    }
    @RequestMapping(value = "/listData",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody Object   listData() throws IOException{
    	List<ZActuatorEntity> actuatorList=sysActuatorMapper.selectList(null);
    	Map<String, List<ZActuatorVo>> groupMap = actuatorList.stream().map(val->{
    		ZActuatorVo vo=new ZActuatorVo();
    		BeanUtils.copyProperties(val, vo);
    		vo.setServerInfo(null);
    		
    		Long mi=((new Date().getTime()- val.getDate().getTime())/1000/60);
    		vo.setOffLineMinits(mi.intValue());
    		if(mi>10) {
    			vo.setOffLine(true);
    		}else {
    			vo.setOnLine(true);
    		}
    			
    		Server Servezzzr=JSONObject.parseObject(val.getServerInfo(),Server.class);
    		vo.setServer(Servezzzr);
    		return vo;
    	}).collect(Collectors.groupingBy(ZActuatorVo::getGroupKey));
    	String str=new Gson().toJson(groupMap);
    	JSONObject info=JSONObject.parseObject(str);
        return info;
    }
    /**
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/listMysqlData",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody Object   listMysqlData() throws IOException{
    	List<MysqlAcutor> actuatorList=mysqlAcutorMapper.selectList(null);
    	
    	
    	Map<String, List<MysqlActuatorVo>> groupMap = actuatorList.stream().map(val->{
    		MysqlActuatorVo vo=new MysqlActuatorVo();
    		BeanUtils.copyProperties(val, vo);
    		vo.setUptime(vo.getUptime()/3600);
    		
    		Long mi=((new Date().getTime()- val.getDate().getTime())/1000/60);
    		vo.setOffLineMinits(mi.intValue());
    		if(mi>10) {
    			vo.setOffLine(true);
    		}else {
    			vo.setOnLine(true);
    		}
    		return vo;
    	}).collect(Collectors.groupingBy(MysqlActuatorVo::getGroupKey));
    	String str=new Gson().toJson(groupMap);
    	JSONObject info=JSONObject.parseObject(str);
    	
        return info;
    }

    

    @ResponseBody
    @RequestMapping("/delete")
	public Res delete(String instanceKey){
    	if(StringUtils.isEmpty(instanceKey)){
    		return Res.error("删除应用不能为空");
    	}
    	try {
    		ZActuatorEntity s=new ZActuatorEntity();
    		s.setInstanceKey(instanceKey);
    		sysActuatorMapper.delete(new QueryWrapper(s));
    		return Res.ok();
		} catch (Exception e){
			logger.debug("删除监控应用异常：{},{}",instanceKey,e);
			return Res.error();
		}
    }
    @ResponseBody
    @RequestMapping("/deleteMysql")
	public Res deleteMysql(String instanceKey){
    	if(StringUtils.isEmpty(instanceKey)){
    		return Res.error("删除应用不能为空");
    	}
    	try {
    		MysqlAcutor s=new MysqlAcutor();
    		s.setInstanceKey(instanceKey);
    		mysqlAcutorMapper.delete(new QueryWrapper(s));
    		return Res.ok();
		} catch (Exception e){
			logger.debug("删除监控应用异常：{},{}",instanceKey,e);
			return Res.error();
		}
    }
    

    @RequestMapping(value = "/userList")
    public String userList(ModelMap model){
    	List<ZUserEntity> list=sysUserMapper.selectList(null);
    	model.addAttribute("list",list);
        return "userList";
    }
      
    @ResponseBody
    @RequestMapping("/saveUser")
    public Res saveUser(String name,String password){
    	try {
    	 	
    		ZUserEntity u=new ZUserEntity();
    		u.setName(name);
    		int count=sysUserMapper.selectCount(new QueryWrapper(u));
    		if(count>0){
    			return Res.error("用户名已存在");
    		}
    		ZUserEntity user=new ZUserEntity();
    		user.setName(name);
    		user.setPassword(Md5.encode(password));
    		sysUserMapper.insert(user);
    		return Res.ok();
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("添加用户异常：{},{}",name,e);
			return Res.error();
		}
    }
    

  
    @ResponseBody
    @RequestMapping("/delUser")
     public Res delUser(int id){
     	try {
     		sysUserMapper.deleteById(id);
     		return Res.ok();
 		} catch (Exception e) {
 			logger.debug("删除用户异常：{}",e);
 			return Res.error();
 		}
     }
     


}
